#!/bin/bash

# Purpose: Find and delete PPDs with duplicate device IDs as the PPDs that are
#          about to be copied to the PPD directory

PPDDIR="/Library/Printers/PPDs/Contents/Resources"
if [ ! -d "${PPDDIR}" ]; then
	mkdir -m 755 "${PPDDIR}"
fi

PKGNAME=`basename "$1"`
TMPDIR=`mktemp -d "/tmp/${PKGNAME}.XXXXXX"`
DEVIDDICT=`mktemp "${TMPDIR}/deviceIDs.XXXXXX"`

# make sure target location is not root
if [ ${2} -eq "/" ]; then
	exit 0
fi

# move PPDs to temporary folder
cd "${2}"
for f in *.[Pp][Pp][Dd]; do
	cp "${f}" "${TMPDIR}/${f}"
	rm -f "${f}"
done

# gather all Device IDs
cd "${TMPDIR}"
grep -m 1 -h "[*]1284DeviceID" *.[Pp][Pp][Dd] | sort -o "${DEVIDDICT}"

OLDIFS=$IFS
IFS=$'\r\n'

# find all PPDs currently copied to PPD directories and look up ID
for f in `find "${PPDDIR}" -regex .*\.[Pp][Pp][Dd]`; do
	DEVID=`sed 's/'$'\\r''/'\\\\$'\n''/g' < "${f}" | grep -m 1 -h "[*]1284DeviceID"`
	look "${DEVID}" "${DEVIDDICT}" > /dev/null
	LOOKSTATUS=$?
	
	# if a device ID was found in the PPD and is found on the ID list -> delete
	if [ 0 -ne ${#DEVID} -a 0 -eq "${LOOKSTATUS}" ]; then
		rm -f "${f}"
	fi
done

# copy new PPDs to PPD directory
for f in *.[Pp][Pp][Dd]; do
	cp "${f}" "${PPDDIR}/${f}"
done

IFS=$OLDIFS

# clean up
cd "/tmp"
rm -rf "${TMPDIR}"